#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Build-in / Std
from bsddb.test.test_compare import cmp

'''
Created on 2016年9月1日

@author: Hawk
'''
import sys
import wx
import MDIChildFrameBase
import BaseDialog
from model.Model import *
from action.Action import *
from ControlID import ControlID

class AddProjectDialog(BaseDialog.BaseDialog):
    def __init__(self, *args, **kwds):
        BaseDialog.BaseDialog.__init__(
            self, None, -1, u'Add SKU',
            style=wx.CAPTION | wx.CLOSE_BOX,
            size=(200, 240))
        self.label_name = wx.StaticText(self, -1, u"名称", pos=(20, 20))
        #self.label_name.SetFont(wx.Font(wx.FONTSIZE_MEDIUM, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL))
        self.textctrl_name = wx.TextCtrl(self, -1, size=(100, 20), pos=(60, 20))


        self.category_list = Category.select().where(Category.deleted == False)
        self.category_list_title = [cat.name for cat in self.category_list]
        self.label_category = wx.StaticText(self, -1, u"类别", pos=(20, 45))
        self.category_choice = wx.Choice(self, -1, (60, 45), choices=self.category_list_title)
        self.category_choice.Bind(wx.EVT_CHOICE, self.OnCategoryChoiceSelect)

        self.label_owner = wx.StaticText(self, -1, u"Owner", pos=(20, 75))
        self.textctrl_owner = wx.TextCtrl(self, -1, size=(100, 20), pos=(60, 75))

        self.label_ee_owner = wx.StaticText(self, -1, u"EE", pos=(20, 105))
        self.textctrl_ee_owner = wx.TextCtrl(self, -1, size=(100, 20), pos=(60, 105))

        self.label_comment = wx.StaticText(self, -1, u"备注", pos=(20, 135))
        self.textctrl_comment = wx.TextCtrl(self, -1, size=(100, 20), pos=(60, 135))

        self.button_save = wx.Button(self, -1, u"保存", pos=(50, 170))
        self.Bind(wx.EVT_BUTTON, self.OnSaveButtonClicked, self.button_save)

    def OnCategoryChoiceSelect(self, event):
        #self.showMessageBox(self.category_choice.GetString(self.category_choice.GetSelection()))
        pass

    def OnSaveButtonClicked(self, event):
        name = self.getTextCtrlValueDefaultNone(self.textctrl_name)

        category_name = self.category_choice.GetString(self.category_choice.GetSelection())
        selected_category = Category.getOne(Category.name == category_name)
        if selected_category is None:
            self.showMessageBox(u'选择类别')
            return

        owner = self.getTextCtrlValueDefaultNone(self.textctrl_owner)
        ee_owner = self.getTextCtrlValueDefaultNone(self.textctrl_ee_owner)

        comment = self.textctrl_comment.GetValue().strip()
        msg = Action().ProjectMgr.add_project(name, selected_category.id, owner, ee_owner, comment)
        if msg:
            self.EndModal(wx.ID_OK)
        else:
            self.showMessageBox(msg.message)

class ProjectMgrFrame(MDIChildFrameBase.MDIChildFrameBase):
    menu_title_in_menubar = "&Project"

    def __init__(self, *args, **kwargs):
        MDIChildFrameBase.MDIChildFrameBase.__init__(self, *args, **kwargs)
        self.InitMenu()

        self.panel = wx.Panel(self)
        self.ListCtrl_ProjectList = wx.ListCtrl(
            self.panel,
            - 1,
            style=wx.LC_REPORT)

        for col, text in enumerate([u'序号', u'id', u'名称', u'类别', u'Owner', u'EE', u'备注']):
            self.ListCtrl_ProjectList.InsertColumn(col, text)

        wx.EVT_LIST_ITEM_RIGHT_CLICK(
            self.ListCtrl_ProjectList,
            - 1,
            self.OnProjectListRightClick)

        self.InitData()

        self.sizer_left = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_left.Add(self.ListCtrl_ProjectList, 1, wx.EXPAND | wx.ALL)
        self.panel.SetSizer(self.sizer_left)
        self.sizer_left.Fit(self)

    def InitData(self):
        self.project_list = Project.select().where(Project.deleted == False)
        self.ListCtrl_ProjectList.DeleteAllItems()
        for idx, item in enumerate(self.project_list):
            index = self.ListCtrl_ProjectList.InsertStringItem(sys.maxint, str(idx + 1))
            self.ListCtrl_ProjectList.SetStringItem(index, 1, str(item.id))
            self.ListCtrl_ProjectList.SetStringItem(index, 2, item.name)
            self.ListCtrl_ProjectList.SetStringItem(index, 3, item.category.name)
            self.ListCtrl_ProjectList.SetStringItem(index, 4, item.owner)
            self.ListCtrl_ProjectList.SetStringItem(index, 5, item.ee_owner)
            self.ListCtrl_ProjectList.SetStringItem(index, 6, item.comment if item.comment is not None else u"")
        self.ListCtrl_ProjectList.SetColumnWidth(0, 45)
        self.ListCtrl_ProjectList.SetColumnWidth(3, 175)
        self.ListCtrl_ProjectList.SetColumnWidth(4, 175)
        self.ListCtrl_ProjectList.SetColumnWidth(5, 175)
        self.ListCtrl_ProjectList.SetColumnWidth(6, 175)

    def InitMenu(self):
        self.menuBar_menubar_menu_items = [
            {'id': ControlID.MENUBAR_MENU_ITEM_SKU_ADD, 'title': u'Add', 'separator': False, 'IsShown': lambda : True},
            {'id': ControlID.MENUBAR_MENU_ITEM_SKU_REFRESH, 'title': u'Refresh', 'separator': False, 'IsShown': lambda : True,
                'hasSub': False,
                'sub' : [{'id': ControlID.MENUBAR_MENU_ITEM_CATEGORY_ADD, 'title': u"导出为CHM(UTF-8)"}]},
            ]
        self.menu = self.BuildMenuItems(self.menuBar_menubar_menu_items, self.OnMenubarMenu_Select)

    def OnMenubarMenu_Select(self, event, menu_item, path):
        id = event.GetId()
        if id == ControlID.MENUBAR_MENU_ITEM_SKU_ADD:
            dlg = AddProjectDialog()
            if wx.ID_OK == dlg.ShowModal():
                self.InitData()
            dlg.Destroy()
        elif id == ControlID.MENUBAR_MENU_ITEM_SKU_REFRESH:
            self.InitData()

    def OnProjectListRightClick(self, event):
        self.selected_row_index = event.GetText()

        self.sku_menu_itemms = [
            {'id': ControlID.SKU_LIST_MENU_VIEW, 'title': u"查看"},
            {'id': ControlID.SKU_LIST_MENU_DELETE, 'title': u"删除"}
            ]

        menu = self.BuildMenuItems(self.sku_menu_itemms, self.OnMenuSelect_SkuList)
        self.PopupMenu(menu, event.GetPoint())
        menu.Destroy()

    def OnMenuSelect_SkuList(self, event, menu_item, path):
        id = event.GetId()
        if id == ControlID.SKU_LIST_MENU_DELETE:
            self.selected_row_index = int(self.selected_row_index) - 1
            msg = Action().ProjectMgr.del_project(self.project_list[self.selected_row_index].id)
            if msg:
                self.InitData()
            else:
                self.showMessageBox(msg.message)
        elif id == ControlID.SKU_LIST_MENU_VIEW:
            self.selected_row_index = int(self.selected_row_index) - 1
            print len(self.project_list[self.selected_row_index].products)
            for p in self.project_list[self.selected_row_index].products:
                print p.project.name, p.sku.name

    def OnActive(self):
        #print '%s has been actived' % self.GetTitle()
        parent_menubar = self.GetParent().GetMenuBar()
        pos = parent_menubar.FindMenu(self.menu_title_in_menubar)
        if pos == -1:
            parent_menubar.Insert(1, self.menu, self.menu_title_in_menubar)

    def OnDeactive(self):
        #print '%s has been deactived' % self.GetTitle()
        parent_menubar = self.GetParent().GetMenuBar()
        pos = parent_menubar.FindMenu(self.menu_title_in_menubar)
        if pos != -1:
            parent_menubar.Remove(pos)

